﻿<%@ WebHandler Language="C#" Class="SyncServer.UploadImage" %>

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Data.Common;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;
using com.SyncConfiguration;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Collections.Generic;


namespace SyncServer
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class UploadImage : IHttpHandler
    {
        private const string SyncConfiguration = "SyncConfiguration";

        public static T JsonDeserialize<T>(string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(ms);
            return obj;

        }

        const string TableSearchKey = "<t n=\"";
        string content = "";

        SyncLogManager logmanger = new SyncLogManager();
        public void ProcessRequest(HttpContext context)
        {
    
            string version = context.Request[SyncServer.LoginConst.VERSION];
            string DOMAINID = context.Request["DOMAINID"];
            string user_code = context.Request["user_code"];
            string requestkey = context.Request[SyncServer.LoginConst.RequestKey];
            string Host = context.Request.UserHostAddress;
            string gzip = context.Request[SyncServer.LoginConst.EnableGZIP];
            bool EnableZip = gzip == null ? true : gzip == "1";
            HttpResponse response = context.Response;
            MemoryStream stream = new MemoryStream();
            SyncServer.MyWriter writer = new SyncServer.MyWriter(stream, EnableZip);
            response.ContentType = ("text/plain;charset=UTF8");
            response.Clear();

            System.Data.IDbTransaction tran = null;
            try
            {
                //获取请求
                byte[] requestData = new byte[context.Request.ContentLength];
                int length = context.Request.InputStream.Read(requestData, 0, requestData.Length);
                requestData = CompressionHelper.DeCompress(requestData);
                length = requestData.Length;
                string RequestContent = System.Text.Encoding.UTF8.GetString(requestData, 0, length);
                JavaScriptSerializer ser = new JavaScriptSerializer();
                var photo = JsonDeserialize<Photo>(RequestContent);//(Photo)ser.Deserialize(RequestContent, typeof(Photo));
                string strPhoto = System.Configuration.ConfigurationManager.AppSettings["ImagePath"].ToString();
                string datapath = DateTime.Now.ToString("yyyyMMdd");
                strPhoto = strPhoto + "\\" + datapath;

                SyncConfigurationSection config = null;
                //验证版本是否正确
                Dictionary<string, SyncConfigurationSection> syncConfig = context.Cache[SyncConfiguration] as Dictionary<string, SyncConfigurationSection>;
                if (syncConfig != null && syncConfig.ContainsKey(version))
                    config = syncConfig[version];
                SyncInterface.IValidate instance = null;
                System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFile(config.FullPath);

                instance = Activator.CreateInstance(assembly.GetType(config.Type.FullName)) as SyncInterface.IValidate;


                try
                {
                    //对图片大小进行判断 1.图片本身为0字节的情况，2.图片上传的大小与写到磁盘文件大小不同不过的情况
                    byte[] byteimg = Convert.FromBase64String(photo.PHOTO_BLOB);
                    try
                    {
                        String upload_photoInfo = String.Format("PHOTO_ID:{0};图片大小：{1}", photo.ID, byteimg.Length);
                        logmanger.AddLog(LogType.PHOTO_SYNC_UPLOAD, upload_photoInfo, "0", user_code, Host);
                    }
                    catch (Exception)
                    {
                        
                    }

                    if (byteimg.Length == 0)
                    {
                        content += setJsonData(photo.ID.ToString(), false,"照片错误：图片大小为0字节", true);
                    }
                    else
                    {
                        if (!Directory.Exists(strPhoto))
                        {
                            Directory.CreateDirectory(strPhoto);
                        }
                        string ext = ".jpg";
                        string name = photo.ID + ext;
                        photo.PHOTO_PATH = datapath + "/" + name;
                        File.WriteAllBytes(strPhoto + "\\" + name, byteimg);

                        if (instance.Connection != null && instance.Connection.State != ConnectionState.Open)
                        {
                            instance.Connection.Open();
                        }

                        using (System.Data.IDbCommand command = instance.Connection.CreateCommand())
                        {
                            command.CommandText =
                                string.Format(@" INSERT INTO PHOTO (ID, USER_ID, VISIT_ID, PHOTO_TYPE_ID, PHOTO_PATH, PHOTO_DATE, DESCRIPTION, ACTIVE, DOMAIN_ID, LAST_UPDATER, LAST_UPDATE_TIME) VALUES(@ID, @USER_ID, @VISIT_ID, @PHOTO_TYPE_ID, @PHOTO_PATH, @PHOTO_DATE, @DESCRIPTION,'{0}','{1}','{2}','{3}')", "1", DOMAINID, photo.USER_ID, DateTime.Now.ToString("yyyyMMddHHmmss"));
                            System.Data.IDbDataParameter param = command.CreateParameter();
                            param.ParameterName = "@ID";
                            param.Value = photo.ID;
                            command.Parameters.Add(param);

                            param = command.CreateParameter();
                            param.ParameterName = "@USER_ID";
                            param.Value = photo.USER_ID;
                            command.Parameters.Add(param);

                            param = command.CreateParameter();
                            param.ParameterName = "@VISIT_ID";
                            param.Value = photo.VISIT_ID;
                            command.Parameters.Add(param);

                            param = command.CreateParameter();
                            param.ParameterName = "@PHOTO_TYPE_ID";
                            param.Value = photo.PHOTO_TYPE_ID;
                            command.Parameters.Add(param);

                            param = command.CreateParameter();
                            param.ParameterName = "@PHOTO_DATE";
                            param.Value = photo.PHOTO_DATE;
                            command.Parameters.Add(param);

                            param = command.CreateParameter();
                            param.ParameterName = "@PHOTO_PATH";
                            param.Value = photo.PHOTO_PATH;
                            command.Parameters.Add(param);

                            param = command.CreateParameter();
                            param.ParameterName = "@DESCRIPTION";
                            param.Value = photo.DESCRIPTION == null ? "" : photo.DESCRIPTION;
                            command.Parameters.Add(param);

                            command.ExecuteNonQuery();
                            content += setJsonData(photo.ID.ToString(), true, "", true);

                        }
                    }
                }
                catch (Exception ex)
                {
                    content += setJsonData(photo.ID.ToString(), false, ex.Message, true);


                }
                catch
                {
                    photo.PHOTO_PATH = "";
                }



                content = "[" + content + "]";
                writer.Write(content);

            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                writer = new MyWriter(stream, EnableZip);
                writer.Write("error:" + ex.Message);
            }
            catch (Exception ex)
            {
                writer = new MyWriter(stream, EnableZip);
                writer.Write("error:" + ex.Message + ex.InnerException);
            }


            writer.Flush();
            writer.Finish();
            if (stream.Length > 0)
            {
                stream.Position = 0;
                stream.WriteTo(response.OutputStream);
            }
            writer.Close();


        }


        /// <summary>
        /// 属性，是否可以再利用
        /// </summary>
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public static string setJsonData(string tablename, bool success, string errmsg, bool end)
        {
            string jsonstring = "";
            System.Text.StringBuilder JsonString = new System.Text.StringBuilder();
            JsonString.Append("\"filename\":\"{0}\",");//json文件名
            JsonString.Append("\"success\":\"{1}\",");//状态
            JsonString.Append("\"errmsg\":\"{2}\"");//错误信息
            jsonstring = string.Format(JsonString.ToString(), tablename, success, errmsg);
            if (!end)
                jsonstring = "{" + jsonstring + "},";
            else
                jsonstring = "{" + jsonstring + "}";
            return jsonstring;
        }
    }




}